package org.lee.validate.handler;

import lombok.extern.slf4j.Slf4j;
import org.lee.validate.custom.BizException;
import org.lee.validate.vo.resp.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * GlobalExceptionHandler
 * 统一异常处理类
 * @author dralee
 * @date 2021-12-24 15:27:43
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException e){
        log.error(e.getMessage(), e);
        return Result.fail(501, e.getMessage());
    }
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e){
        log.error(e.getMessage(), e);
        return Result.fail(411, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidationException(MethodArgumentNotValidException e){
        log.error(e.getMessage(), e);
        return Result.fail(411, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e){
        log.error(e.getMessage(), e);
        return Result.fail(412, e.getCause().getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException e){
        log.error(e.getMessage(), e);
        return Result.fail(413, e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return Result.fail(414, "数据重复，请检查".concat(e.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error(e.getMessage(), e);
        return Result.fail(500, "系统繁忙，请稍后重试".concat(e.getMessage()));
    }
}
